package com.hotau.member;

import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TableLayout;

import com.hotau.Executable;
import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.framework.IndexFragment;
import com.hotau.member.service.MemberService;
import com.hotau.member.vo.User;
import com.hotau.push.PushService;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpRequestAsynTask;
import com.hotau.util.HttpUtil;
import com.hotau.util.PreferencesUtils;
import com.hotau.util.ValidateUtils;

/**
 * 用户登陆
 * @author liujia (liujia9234@126.com)
 * @data 2011-12-9
 * @version 1.0
 * <ul>
 * 		<li>1.0 创建</li>
 * </ul>
 */
public class LoginFragment extends Fragment implements OnClickListener,IndexFragment{
    public static final int MAX_PASSWORD_LENGTH = 20;
	public static final String TAG = "LoginFragment";
	private EditText login_et_usercode = null;
	private EditText login_et_loginpwd = null;
	private CheckBox login_cb = null;
	private Button login_btn = null;
	private TableLayout login_layout_findpwd = null;
	private ImageButton login_usercode_btn_clear = null;
	private SharedPreferences share = null;
	private SharedPreferences.Editor  shareEdit = null;
	private User user = null;
	private HotauActivity csmbpActivity = null;
	/**
	 * 异步请求Task
	 */
	HttpRequestAsynTask login_task = null; //登陆
	
	private String fragmentNeedLoginName;
	private Fragment fragmentNeedLogin;
	private boolean finishLogin = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if(this.getArguments() != null) {
			finishLogin = this.getArguments().getBoolean("finishLogin");
			fragmentNeedLoginName = this.getArguments().getString("fragmentNeedLoginName");
			fragmentNeedLogin = (Fragment)this.getArguments().get("fragmentNeedLogin");
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		csmbpActivity = (HotauActivity) getActivity();
		share = csmbpActivity.getSharedPreferences("MEMBER_USER",0);
		shareEdit = share.edit();
		initAllWidget();
		initAllEvent();
		MemberService.logout(csmbpActivity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.member_login, container,false);
	}

	public String pushSwitchService(String pushSwitch, String usrCode) {
		
       
        String terminalCode = HotauConstants.getTerminalCode(LoginFragment.this.getActivity());
        String terminalType = "1";
        String request = "Form:userCode=" + usrCode + ";pushSwitch=" +
        	pushSwitch + ";icloudToken=Android;terminalCode=" + terminalCode + ";terminalType=" + terminalType;
        
		String result = HttpUtil.doHttp(60000, 60000, HotauConstants.PUSH_SWITCH_URL,
                request, HttpUtil.HTTP_POST, HttpUtil.UTF8_ENCODING, false);
		
		return result;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.member_login_btn:
//			DialogUtil.showDialog(getActivity(), "", MemberService.isLogin(getActivity())+","+MemberService.getToken(getActivity()));
			user = new User();
			user.userCode = login_et_usercode.getText().toString();
			user.loginPwd = login_et_loginpwd.getText().toString();
			user.terminalCode = HotauConstants.getTerminalCode(getActivity());
			user.sign = "";
			
			if(user.isCheck()){
				if(login_et_loginpwd.getText().length() < 8 ){
					DialogUtil.showDialog(csmbpActivity, "", "密码长度过短");
				}else{
					login_task = new HttpRequestAsynTask(csmbpActivity){
						@Override
						protected void doPostExecute(String result) {
							// TODO Auto-generated method stub	
							Log.d(TAG, "login_response :" + result);
							try {
								JSONObject login_result = new JSONObject(result);
								login_result.put("lastDate", new Date().getTime());
								shareEdit.putString("login_user_info",login_result.toString());
								
								if(login_result != null && login_result.getInt("result") == 1 && login_result.has("token")){
									

									final String newUserCode = login_et_usercode.getText().toString();
									final String oldUserCode = MemberService.getUserCode(context);
									
									if (!newUserCode.equals(oldUserCode)) {
										Dialog dialog = new AlertDialog
											.Builder(context)
											.setTitle("提示")
											.setMessage("您是否接受“新生易游”给你发送推送通知消息?")
											.setNegativeButton("不接受", new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog,
														int which) {
													
													dialog.dismiss();
													String result = pushSwitchService("N", newUserCode);
													Log.d(TAG, "Turn on push switch, the callback result is :" 
															+ result);
													try {
														JSONObject switchResult = new JSONObject(result);
														if (switchResult != null && switchResult.getInt("result") == 1) {
															
															Intent serviceOff = new Intent(context, PushService.class);
															context.stopService(serviceOff);
															
															PreferencesUtils.setReceive(context, PreferencesUtils.VALUE_PUSH_OFF);
															Log.d(TAG,
																	"PreferencesUtils receive off:"
																			+ PreferencesUtils.getReceive(context));
														} else {
															if (switchResult != null)
																Log.d(TAG, "关闭推送功能失败;errorCode=" 
																		+ switchResult.getInt("errorCode")
																			+ ";errorMsg=" + switchResult.getString("errorMsg"));
															DialogUtil.alertDialog(context, "系统繁忙，请稍后再试!");
														}
													} catch (JSONException e) {
														
													}
												}
											})
											.setPositiveButton("接受", new DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													
													  dialog.dismiss();
														
													  String result = pushSwitchService("Y", newUserCode);
										        		Log.d(TAG, "Turn on push switch, the callback result is :" 
										        					+ result);
										        		try {
										        			JSONObject switchResult = new JSONObject(result);
										        			if (switchResult != null && switchResult.getInt("result") == 1) {
										        				Intent serviceOn = new Intent(context, PushService.class);
										        				context.stopService(serviceOn);
										        				context.startService(serviceOn);
										                        
										                        PreferencesUtils.setReceive(context, PreferencesUtils.VALUE_PUSH_ON);
											                    
											                    Log.d(TAG,
											                            "PreferencesUtils receive on:"
											                                    + PreferencesUtils.getReceive(context));
										        			} else {
										        				if (switchResult != null)
										        					Log.d(TAG, "开启推送功能失败;errorCode=" 
										        							+ switchResult.getInt("errorCode") 
										        								+ ";errorMsg=" + switchResult.getString("errorMsg"));
										        				
										        				DialogUtil.alertDialog(context, "系统繁忙，请稍后再试!");
										        			}
									        			} catch (JSONException e) {
									        				
									        			}
												}
											}).create();
										
										dialog.show();
									} else {
										//登录成功提示
										DialogUtil.showDialog(csmbpActivity, "", "登录成功!");
									}
									
									shareEdit.putString("last_login_usercode", login_et_usercode.getText().toString());
									//登录成功
									if(login_cb.isChecked()){
										//记住密码
										shareEdit.putString("user_usercode", newUserCode);
										shareEdit.putString("user_loginpwd", login_et_loginpwd.getText().toString());
									}else{
										shareEdit.putString("user_usercode", "");
										shareEdit.putString("user_loginpwd", "");
									}
									shareEdit.commit();
									//或者账户信息
									hander.sendEmptyMessage(1);
									//跳转到首页
									Fragment cc = fragmentNeedLogin;
									if (cc != null) {
										if (finishLogin) {
											csmbpActivity.popFragment();
										}
										
										csmbpActivity.pushFragment(fragmentNeedLoginName, cc);
									}else {
										csmbpActivity.toHome();
									}
								}else if(login_result.getInt("result") == 0 && login_result.has("errorCode")){
									//登录失败
									int errorCode = login_result.getInt("errorCode");
									switch (errorCode) {
									case 3:
									    String message = "";
									    if(ValidateUtils.isEmail(login_et_usercode.getText().toString()))
									    {
									        message = "提示用户未激活，请登录网页版激活。";
									    }
									    else
									    {
									        message = "账号尚未激活，激活短信将会发送至您的手机，请注意查收。";
									    }
										DialogUtil.showDialog(csmbpActivity, "", message,new Executable() {
											@Override
											public void execute() {
												// TODO Auto-generated method stub
												csmbpActivity.toHome();
											}
										});
										break;
									default:
										DialogUtil.showDialog(csmbpActivity, "", login_result.getString("errorMsg"));
										break;
									}
								}
								shareEdit.commit();
//								if((login_result.getInt("result") == 0 && login_result.getInt("errorCode")==3)){
//									csmbpActivity.pushFragment("信息提示", new LoginActivateFragment(false));
//
//								}else if((login_result.getInt("result") == 0 && login_result.getInt("errorCode")==6)){
//									if (fragmentNeedLogin != null) {
//										if (finishLogin) {
//											csmbpActivity.popFragment();
//										}
//										csmbpActivity.pushFragment(fragmentNeedLoginName, fragmentNeedLogin);
//									}else {
//										csmbpActivity.toHome();
//									}
//								}else if(login_result != null && login_result.getInt("result") == 1 ){
//									shareEdit.remove("login_user_info");
//									//登陆成功
//									if(login_cb.isChecked()){
//										//记住密码
//										shareEdit.putString("user_usercode", login_et_usercode.getText().toString());
//										shareEdit.putString("user_loginpwd", login_et_loginpwd.getText().toString());
//									}else{
//										shareEdit.putString("user_usercode", "");
//										shareEdit.putString("user_loginpwd", "");
//									}
//									user.memberCode = login_result.getString("memberCode");
//									shareEdit.putString("login_token", login_result.getString("token"));
//									shareEdit.putString("login_member_code", user.memberCode);
//									shareEdit.putLong("login_date", new Date().getTime());
//									shareEdit.commit();
//									if (fragmentNeedLogin != null) {
//										if (finishLogin) {
//											csmbpActivity.popFragment();	
//										}
//										csmbpActivity.pushFragment(fragmentNeedLoginName, fragmentNeedLogin);
//									}else {
//										csmbpActivity.toHome();
//									}
//								}else{
//									//登陆失败
//									DialogUtil.showDialog(getActivity(), "", login_result.getString("errorMsg"));
//								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								DialogUtil.showDialog(csmbpActivity, "", "登陆返回数据出错 ");
							}
						}
					};
					login_task.execute(HotauConstants.MEMBER_LOGIN_URL,user.getLoginRequestText(getActivity()),HttpUtil.UTF8_ENCODING);
					Log.d(TAG, "login_request :" + user.getLoginRequestText(getActivity()));
				}
			}else{
				DialogUtil.showDialog(csmbpActivity, "", "用户名必须手机号码或邮箱");
			}
			break;
		case R.id.member_login_layout_findpwd:
			Bundle bundle = new Bundle();
			bundle.putString("loginName", login_et_usercode.getText().toString());
			LostPwdFragment pdf = new LostPwdFragment();
			pdf.setArguments(bundle);
			csmbpActivity.pushFragment("找回登录密码", pdf);
			break;
		case R.id.member_login_usercode_btn_clear:
			login_et_usercode.setText("");
			break;
		default:
			break;
		}
	}
	
	/**
	 * 初始化所有控件
	 */
	public void initAllWidget() {
		login_cb = (CheckBox) csmbpActivity.findViewById(R.id.member_login_cb);
		login_et_usercode = (EditText) csmbpActivity.findViewById(R.id.member_login_et_usercode);
		login_et_loginpwd = (EditText) csmbpActivity.findViewById(R.id.member_login_et_loginpwd);
		login_et_loginpwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_PASSWORD_LENGTH)});  
		
		if(!"".equals(share.getString("user_usercode", "")) && !"".equals(share.getString("user_loginpwd", ""))){
			login_cb.setChecked(true);
			login_et_usercode.setText(share.getString("user_usercode", ""));
			login_et_loginpwd.setText(share.getString("user_loginpwd", ""));
		}else{
			login_cb.setChecked(false);
			login_et_usercode.setText(share.getString("last_login_usercode", ""));
			login_et_loginpwd.setText("");
		}
		
		login_btn = (Button) csmbpActivity.findViewById(R.id.member_login_btn);
		login_layout_findpwd = (TableLayout) csmbpActivity.findViewById(R.id.member_login_layout_findpwd);
		login_usercode_btn_clear = (ImageButton) csmbpActivity.findViewById(R.id.member_login_usercode_btn_clear);
	}
	
	/**
	 * 初始化所有事件
	 */
	public void initAllEvent() {
		login_btn.setOnClickListener(this);
		login_layout_findpwd.setOnClickListener(this);
		login_usercode_btn_clear.setOnClickListener(this);
	}
	
	public Handler hander = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			StringBuilder sb_edit_pwd = new StringBuilder();
			sb_edit_pwd.append("Form:token="+MemberService.getToken(csmbpActivity));
			sb_edit_pwd.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
			HttpRequestAsynTask account_info_task = new HttpRequestAsynTask(csmbpActivity){
				@Override
				protected void doPostExecute(String result) {
					try {
						JSONObject data = new JSONObject(result);
						if(data != null && data.getInt("result") == 1){
							shareEdit.putString("account_user_info", data.toString());
							shareEdit.commit();
						}else{
							//用户信息获取失败
							//DialogUtil.showDialog(csmbpActivity, "",data.getString("errorMsg") );
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						//DialogUtil.showDialog(csmbpActivity, "", "账号信息查询返回数据出错 ");
					}
				}
			};
			account_info_task.setShowProgressDialog(false);
			account_info_task.execute(HotauConstants.ACCOUNT_QUERY_INFO,sb_edit_pwd.toString(),HttpUtil.UTF8_ENCODING);
		}
		
	};
	
	
}
